﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace T03ChatServer
{
    class HandleClient
    {
        private Socket clientSocket;
        private string clientNo;
        private Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();

        public void StartClient(Socket clientSocket,string clientNo,Dictionary<string,Socket> clientList )
        {
            this.clientSocket = clientSocket;
            this.clientNo = clientNo;
            this.clientList = clientList;
            Thread t = new Thread(Chat);
        }

        private void Chat()
        {
            byte[] bytesFromClient = new byte[4096];
            string dataFromClient;
            string msgTemp = null;
            byte[] bytesSend = new byte[4096];
            bool isListen = true;

            try
            {
                //处理客户端信息
                int len = clientSocket.Receive(bytesFromClient);
                dataFromClient = Encoding.UTF8.GetString(bytesFromClient, 0, len);
                if (!string.IsNullOrWhiteSpace(dataFromClient))
                {
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.LastIndexOf("$"));
                    if (!string.IsNullOrWhiteSpace(dataFromClient))
                    {
                        //有效发送给所有的客户端
                    }
                    else
                    {
                        //客户端只发送一个“$”，表明主动关闭连接
                        //从字典中移除,当前用户
                        clientList.Remove(clientNo);
                        clientSocket.Close();
                        clientSocket = null;
                        isListen = false;
                    }
                }

            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                clientList.Remove(clientNo);
                clientSocket.Close();
                clientSocket = null;
                isListen = false;

            }
        }
    }
}
